package com.udaos.modules.physical.services;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import com.udaos.common.base.AppException;
import com.udaos.common.base.Service;
import com.udaos.common.util.DateUtil;
import com.udaos.models.physical.Ud_physical_code;
import com.udaos.models.physical.Ud_physical_code_batch;
import com.udaos.modules.physical.utils.CodeUtil;


@IocBean(args = { "refer:dao" })
public class UdPhysicalCodeService extends Service<Ud_physical_code>{
	
	@Inject
	private UdPhysicalCodeBatchService batchService;

	public UdPhysicalCodeService(Dao dao) {
		super(dao);
	}

	/**
	 * 新增code
	 * @param count
	 * @throws AppException 
	 */
	@Aop(TransAop.READ_COMMITTED)
	public void createCode(Integer count,String batch_no) throws AppException {
		if(count >0 && null !=batch_no){
			//1.判断批次号是否存在
			List<Ud_physical_code_batch> batchList=batchService.query(Cnd.where("batch_no", "=", batch_no));
			if(null !=batchList && batchList.size()>0){
				throw new AppException("当前批次号已经存在");
			}
			//2.创建批次
			Ud_physical_code_batch batch=new Ud_physical_code_batch();
			batch.setBatch_count(count);
			batch.setBatch_no(batch_no);
			batch.setCreateAt((int)(System.currentTimeMillis()/1000));
			batch.setState(0);
			batchService.insert(batch);
			//3.生成当前批次体检码
			List<Ud_physical_code> codeList=new ArrayList<Ud_physical_code>();
			for(int i=1;i<=count;i++){
				Ud_physical_code code=new Ud_physical_code();
				code.setSn(batch_no+String.format("%04d", i)); 
				code.setCode(CodeUtil.getCode());
				code.setBatch_id(batch.getId());
				code.setState(0);
				code.setCreateAt((int)(System.currentTimeMillis()/1000));
				codeList.add(code);
			}
			dao().insert(codeList);
		}
	}
	/**
	 * 获取当前主体下的一个任意有效的体检码
	 * @param companyId
	 * @return
	 */
	public String getCode(){
		List<Ud_physical_code_batch> batchs=batchService.query(Cnd.where("state", "=", 1));
		if(null == batchs || batchs.size()<=0){
			return null;
		}
		List<String> ids=new ArrayList<String>();
		for(Ud_physical_code_batch batch:batchs){
			ids.add(batch.getId());
		}
		Cnd cnd=Cnd.NEW();
		cnd.and("state", "=", 0);
		cnd.and("delFlag", "=", 0);
		cnd.and("batch_id", "IN", ids);
		cnd.asc("sn");
		List<Ud_physical_code> codes=this.query(cnd);
		if(null !=codes && codes.size()>0){
			return codes.get(0).getSn()+"-"+codes.get(0).getCode();
		}
		return null;
	}

	
}
